<template>
  <div>
    <a-card>
      <a-space>
        <a-input
          v-model:value="listQuery.username"
          placeholder="输入账号搜索"
          allow-clear
          @keyup.enter="handleFilter"
        />
        <a-select
          v-model:value="listQuery.locked"
          allow-clear
          :options="[
            { label: '冻结', value: 1 },
            { label: '正常', value: 0 },
          ]"
          placeholder="是否冻结"
          style="width: 100px"
          @change="handleFilter"
        />
        <a-button type="primary" :icon="h(SearchOutlined)" @click="handleFilter">搜索</a-button>
      </a-space>
    </a-card>
    <a-card class="mt-2">
      <a-space class="mb-4">
        <a-button
          :icon="h(PlusOutlined)"
          v-if="hasPermission(['user:add'])"
          type="primary"
          @click="handleAdd"
        >
          添加用户
        </a-button>
        <a-button :icon="h(DownloadOutlined)" @click="handleExport">导出数据</a-button>
        <a-button
          v-if="checkedRowKeysRef.length && hasPermission(['user:delete'])"
          type="primary"
          danger
          :icon="h(DeleteOutlined)"
          @click="handleBatchDelete"
        >
          批量删除
        </a-button>
      </a-space>
      <a-table
        ref="table"
        bordered
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        :loading="tableLoading"
        :row-key="(row) => row.userId + ''"
        :row-selection="
          hasPermission(['user:delete'])
            ? {
                fixed: true,
                preserveSelectedRowKeys: true,
                selectedRowKeys: checkedRowKeysRef,
                onChange: handleCheck,
              }
            : null
        "
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'locked'">
            <a-tag :color="record.locked ? '' : 'success'">
              {{ record.locked ? '冻结' : '正常' }}
            </a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'actions'">
            <a-button
              v-if="hasPermission(['user:edit'])"
              size="small"
              type="link"
              @click="handleEdit(record)"
            >
              <a-tooltip>
                <template #title>编辑</template>
                <EditOutlined />
              </a-tooltip>
            </a-button>
            <a-button
              v-if="hasPermission(['user:delete'])"
              size="small"
              type="link"
              danger
              @click="handleDelete(record)"
            >
              <a-tooltip>
                <template #title>删除</template>
                <DeleteOutlined />
              </a-tooltip>
            </a-button>
            <a-button
              v-if="hasPermission(['user:reset'])"
              size="small"
              type="link"
              @click="handleResetPwd(record)"
            >
              <a-tooltip>
                <template #title>重置密码</template>
                <UndoOutlined />
              </a-tooltip>
            </a-button>
          </template>
        </template>
      </a-table>
    </a-card>
    <a-modal
      v-model:open="showModal"
      :mask-closable="false"
      :title="title"
      :confirm-loading="formBtnLoading"
      @ok="handleConfirm"
    >
      <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 3 }" class="pt-1">
        <a-form-item label="账号" name="username">
          <a-input
            v-model:value="form.username"
            placeholder="请输入账号"
            show-count
            allow-clear
            :maxlength="20"
          />
        </a-form-item>
        <a-form-item label="姓名" name="nickname">
          <a-input
            v-model:value="form.nickname"
            placeholder="请输入姓名"
            show-count
            allow-clear
            :maxlength="12"
          />
        </a-form-item>
        <a-form-item label="手机" name="phone">
          <a-input
            v-model:value="form.phone"
            placeholder="请输入手机"
            show-count
            allow-clear
            :maxlength="11"
          />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="form.email" allow-clear placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item label="角色" name="roleIds">
          <a-select
            v-model:value="form.roleIds"
            mode="multiple"
            :options="roleList"
            option-filter-prop="roleName"
            :field-names="{
              label: 'roleName',
              value: 'roleId',
            }"
          />
        </a-form-item>
        <a-form-item label="冻结" name="locked">
          <a-switch v-model:checked="form.locked" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { h, onMounted, reactive, ref, watch } from 'vue';
  import UserApi from '@/api/UserApi';
  import {
    DeleteOutlined,
    DownloadOutlined,
    EditOutlined,
    PlusOutlined,
    SearchOutlined,
    UndoOutlined,
  } from '@ant-design/icons-vue';
  import RoleApi from '@/api/RoleApi';
  import { usePermission } from '@/hooks/usePermission';
  import { download, resetReactive } from '@/utils';
  import { message, Modal } from 'ant-design-vue';
  import { Rule } from 'ant-design-vue/es/form';

  const { hasPermission } = usePermission();

  let columns = [
    { title: '账号', dataIndex: 'username' },
    { title: '姓名', dataIndex: 'nickname' },
    { title: '手机', dataIndex: 'phone' },
    {
      title: '邮箱',
      dataIndex: 'email',
      ellipsis: true,
    },
    {
      title: '是否冻结',
      dataIndex: 'locked',
      align: 'center',
      width: 100,
    },
    { title: '创建时间', dataIndex: 'createTime', width: 180 },
    { title: '更新时间', dataIndex: 'updateTime', width: 180 },
  ];
  const actionColum = {
    title: '操作',
    dataIndex: 'actions',
    align: 'center',
    fixed: 'right',
    width: 130,
  };

  if (hasPermission(['user:edit', 'user:delete', 'user:reset'])) {
    columns.push(actionColum);
  }

  let data = ref([]);
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    onChange: (current, pageSize) => {
      pagination.current = current;
      pagination.pageSize = pageSize;
      getList();
    },
  });
  onMounted(() => {
    getRoleList();
    getList();
  });

  const listQuery = reactive<any>({});

  const tableLoading = ref(false);

  function getList() {
    tableLoading.value = true;
    UserApi.page({ index: pagination.current, size: pagination.pageSize, ...listQuery })
      .then((res) => {
        data.value = res.data;
        pagination.total = res.total;
      })
      .finally(() => (tableLoading.value = false));
  }

  const roleList = ref<Role[]>([]);

  function getRoleList() {
    RoleApi.list({}).then((res) => {
      roleList.value = res.data;
    });
  }

  function getCheckedRoles() {
    UserApi.getRoles(form.userId).then((res) => {
      form.roleIds = res.data;
    });
  }

  function handleFilter() {
    pagination.current = 1;
    getList();
  }

  const showModal = ref(false);
  const title = ref('');
  const formRef = ref();
  const form = reactive<User>({});
  const rules: Record<string, Rule[]> = {
    username: [{ required: true, trigger: 'blur', message: '请输入账号' }],
    roleIds: [{ required: true, trigger: ['blur', 'change'], message: '请选择角色' }],
  };

  watch(
    () => form.phone,
    (val, preVal) => {
      const reg = /^\d*$/;
      if (reg.test(val) || val === '') {
        form.phone = val;
      } else {
        form.phone = preVal;
      }
    }
  );

  function handleEdit(row) {
    showModal.value = true;
    title.value = '编辑';
    Object.assign(form, row);
    formRef.value?.clearValidate();
    getCheckedRoles();
  }

  function handleAdd() {
    showModal.value = true;
    title.value = '添加';
    resetReactive(form);
    formRef.value?.clearValidate();
  }

  const formBtnLoading = ref(false);

  function handleConfirm() {
    formRef.value
      .validate()
      .then(() => {
        formBtnLoading.value = true;
        (form.userId ? UserApi.update(form) : UserApi.save(form))
          .then(() => {
            message.success('提交成功');
            showModal.value = false;
            getList();
          })
          .finally(() => {
            formBtnLoading.value = false;
          });
      })
      .catch(() => {});
  }

  function handleDelete(row) {
    Modal.confirm({
      title: '提示',
      content: '确定删除这条记录吗？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        UserApi.delete([row.userId]).then(() => {
          message.success('操作成功');
          getList();
        });
      },
      onCancel: () => {},
    });
  }

  function handleResetPwd(row) {
    Modal.confirm({
      title: '提示',
      content: '此操作将重置该账号密码, 是否继续?',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        UserApi.resetPwd(row).then(() => {
          message.success('操作成功！密码已重置为123456');
          getList();
        });
      },
      onCancel: () => {},
    });
  }

  const checkedRowKeysRef = ref([]);

  function handleCheck(rowKeys: string[]) {
    checkedRowKeysRef.value = rowKeys;
  }

  function handleBatchDelete() {
    Modal.confirm({
      title: '提示',
      content: `确定删除所选的${checkedRowKeysRef.value.length}条数据吗?`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        UserApi.delete(checkedRowKeysRef.value).then(() => {
          message.success('操作成功！');
          checkedRowKeysRef.value = [];
          handleFilter();
        });
      },
      onCancel: () => {},
    });
  }

  function handleExport() {
    UserApi.export().then((res) => {
      download(res.data, '人员数据.xlsx');
    });
  }
</script>

<style scoped></style>
